package com.taiyi.renaissancemall.ui.mine.updateUser;

import android.content.Intent;
import android.net.Uri;
import android.os.Bundle;
import android.os.Environment;
import android.os.PersistableBundle;
import android.text.TextUtils;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.constraintlayout.widget.ConstraintLayout;

import com.alibaba.sdk.android.oss.ClientException;
import com.alibaba.sdk.android.oss.OSSClient;
import com.alibaba.sdk.android.oss.ServiceException;
import com.alibaba.sdk.android.oss.callback.OSSCompletedCallback;
import com.alibaba.sdk.android.oss.callback.OSSProgressCallback;
import com.alibaba.sdk.android.oss.internal.OSSAsyncTask;
import com.alibaba.sdk.android.oss.model.PutObjectRequest;
import com.alibaba.sdk.android.oss.model.PutObjectResult;
import com.bumptech.glide.Glide;
import com.bumptech.glide.load.resource.bitmap.CircleCrop;
import com.bumptech.glide.request.RequestOptions;
import com.taiyi.renaissancemall.R;
import com.taiyi.renaissancemall.Utils.ToastUtils;
import com.taiyi.renaissancemall.base.BaseActivity;
import com.taiyi.renaissancemall.base.MyApp;
import com.taiyi.renaissancemall.bean.PersonInfoBean;
import com.taiyi.renaissancemall.bean.VerifiedBean;
import com.taiyi.renaissancemall.ui.mine.verified.BaseBottomView;

import org.devio.takephoto.app.TakePhoto;
import org.devio.takephoto.app.TakePhotoActivity;
import org.devio.takephoto.app.TakePhotoImpl;
import org.devio.takephoto.model.InvokeParam;
import org.devio.takephoto.model.TContextWrap;
import org.devio.takephoto.model.TResult;
import org.devio.takephoto.permission.InvokeListener;
import org.devio.takephoto.permission.PermissionManager;
import org.devio.takephoto.permission.TakePhotoInvocationHandler;

import java.io.File;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;

public class UpdateUserActivity extends BaseActivity<UpdateUserView, UpdateUserPresent> implements UpdateUserView, TakePhoto.TakeResultListener, InvokeListener {

    @BindView(R.id.iv_update_icon)
    ImageView ivUpdateIcon;
    @BindView(R.id.imageView2)
    ImageView imageView2;
    @BindView(R.id.et_update_name)
    TextView etUpdateName;
    @BindView(R.id.tv_commit_update)
    TextView tvCommitUpdate;
    @BindView(R.id.backIv)
    ImageView backIv;
    @BindView(R.id.titleTv)
    TextView titleTv;
    @BindView(R.id.rightIv)
    ImageView rightIv;
    @BindView(R.id.top)
    ConstraintLayout top;

    private TakePhoto takePhoto;
    private BaseBottomView bottomView;
    private InvokeParam invokeParam;
    private static final String TAG = TakePhotoActivity.class.getName();
    private String mImagePath = Environment.getExternalStorageDirectory() + "";
    private String mImageName = "/wanlimall/" + System.currentTimeMillis() + ".jpg";
    private String path = "";
    private Uri imageUri = null;
    private TextView headChangePopupBlack;
    private Button takePhotoBtn;
    private Button pickPhotoBtn;
    private Button cancelBtn;
    private boolean isXiangCe = false;
    private String iconPath = "";
    private String frount_photo = "";
    private boolean isChoose = true;
    private String oldName = "";
    private String oldIcon = "";
    private String getOSSUrl = "";

    @Override
    protected int getLayoutId() {
        return R.layout.activity_update_user;
    }

    @Override
    public UpdateUserPresent initPresenter() {
        return new UpdateUserPresent();
    }

    @Override
    protected void initViews(Bundle savedInstanceState) {
        getTakePhoto().onCreate(savedInstanceState);
        titleTv.setText(getString(R.string.userInfo));

        //设置点击图片的弹框显示
        bottomView = new BaseBottomView(this, R.layout.act_photo);
        headChangePopupBlack = ((TextView) bottomView.findViewById(R.id.headChangePopupBlackId));
        takePhotoBtn = (Button) bottomView.findViewById(R.id.takePhotoBtnId);
        pickPhotoBtn = (Button) bottomView.findViewById(R.id.pickPhtotBtnId);
        cancelBtn = (Button) bottomView.findViewById(R.id.cancel_btnId);
        bottomView.setCancelable(true);

        //关闭选择界面
        cancelBtn.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                bottomView.dismiss();
            }
        });

        //选择相册
        pickPhotoBtn.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                isXiangCe = true;
                imageUri = getImageCropUri();
                //从相册中选取不裁剪
                takePhoto.onPickFromGallery();
            }
        });

        //选择拍照
        takePhotoBtn.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                isXiangCe = false;
                imageUri = getImageCropUri();
                //仅仅拍照不裁剪
                takePhoto.onPickFromCapture(imageUri);
            }
        });

        headChangePopupBlack.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                bottomView.dismiss();
            }
        });

    }

    @Override
    protected void initImmersionBar() {
        super.initImmersionBar();
        mImmersionBar.titleBar(top).init();
    }

    @Override
    protected void initData() {
        if (isChoose) {
            showProgress();
            presenter.getPersonInfo();
        }
    }

    @Override
    public void initEvent() {

    }

    @Override
    public void getPersonInfoSuccess(PersonInfoBean personInfoBean) {
        hideProgress();
        if ("".equals(personInfoBean.getRealname()) || personInfoBean.getRealname() == null) {
            etUpdateName.setText(personInfoBean.getTel());
            oldName = personInfoBean.getTel();
        } else {
            etUpdateName.setText(personInfoBean.getRealname());
            oldName = personInfoBean.getRealname();
        }
        if (personInfoBean.getHeadimg() != null && !"".equals(personInfoBean.getHeadimg())) {
            Glide.with(this).load(personInfoBean.getHeadimg()).apply(RequestOptions.bitmapTransform(new CircleCrop())).into(ivUpdateIcon);
            oldIcon = personInfoBean.getHeadimg();
        }
    }

    @Override
    public void getPersonInfoFailure(String msg) {
        hideProgress();
        ToastUtils.showLongToast(msg);
    }

    @Override
    public void toUpdateUserIconSuccess(VerifiedBean verifiedBean) {
        hideProgress();
        ToastUtils.showLongToast("头像修改成功");
        if (!oldName.equals(etUpdateName.getText().toString().trim())) {
            presenter.updateName(etUpdateName.getText().toString().trim());
        } else {
            finish();
        }
    }

    @Override
    public void toUpdateUserIconFailure(String msg) {
        ToastUtils.showLongToast(msg);
    }

    @Override
    public void toUpdateUserNameSuccess(String msg_cn) {
        hideProgress();
        finish();
        ToastUtils.showLongToast("昵称修改成功");
    }

    @Override
    public void toUpdateUserNameFailure(String msg) {
        ToastUtils.showLongToast(msg);
    }

    @OnClick({R.id.iv_update_icon, R.id.et_update_name, R.id.tv_commit_update, R.id.backIv})
    public void onViewClicked(View view) {
        switch (view.getId()) {
            case R.id.iv_update_icon:
                bottomView.show();
                break;
            case R.id.tv_commit_update:
                if (!oldIcon.equals(frount_photo) && !"".equals(frount_photo)) {
                    showProgress();
                    presenter.updateHeadImg(frount_photo);
                } else {
                    if (!oldName.equals(etUpdateName.getText().toString().trim())) {
                        showProgress();
                        presenter.updateName(etUpdateName.getText().toString().trim());
                    } else {
                        ToastUtils.showLongToast("尚无修改变动");
                    }
                }
                break;
            case R.id.backIv:
                finish();
                break;
        }
    }

    @Override
    public void onSaveInstanceState(@NonNull Bundle outState, @NonNull PersistableBundle outPersistentState) {
        getTakePhoto().onSaveInstanceState(outState);
        super.onSaveInstanceState(outState, outPersistentState);
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, @Nullable Intent data) {
        getTakePhoto().onActivityResult(requestCode, resultCode, data);
        super.onActivityResult(requestCode, resultCode, data);
    }

    @Override
    public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults);
        PermissionManager.TPermissionType type = PermissionManager.onRequestPermissionsResult(requestCode, permissions, grantResults);
        PermissionManager.handlePermissionsResult(this, type, invokeParam, this);
    }

    /**
     * 获取TakePhoto实例
     *
     * @return
     */
    public TakePhoto getTakePhoto() {
        if (takePhoto == null) {
            takePhoto = (TakePhoto) TakePhotoInvocationHandler.of(this).bind(new TakePhotoImpl(this, this));
        }
        return takePhoto;
    }

    @Override
    public void takeSuccess(TResult result) {
        isChoose = false;
        if (bottomView.isShowing()) {
            bottomView.dismiss();
        }
        iconPath = result.getImage().getOriginalPath();
        if (isXiangCe) {
            uploadFileToOSS(iconPath);
            Glide.with(UpdateUserActivity.this).load(iconPath).apply(RequestOptions.bitmapTransform(new CircleCrop())).into(ivUpdateIcon);
            frount_photo = getOSSUrl;
        } else {
            uploadFileToOSS(path);
            Glide.with(UpdateUserActivity.this).load(path).apply(RequestOptions.bitmapTransform(new CircleCrop())).into(ivUpdateIcon);
            frount_photo = getOSSUrl;
        }
        Log.i(TAG, "takeSuccess：" + result.getImage().getCompressPath() + "==" + result.getImage().getOriginalPath());
    }

    @Override
    public void takeFail(TResult result, String msg) {
        Log.i(TAG, "takeFail:" + msg);
    }

    @Override
    public void takeCancel() {
        Log.i(TAG, getResources().getString(R.string.msg_operation_canceled));
    }

    @Override
    public PermissionManager.TPermissionType invoke(InvokeParam invokeParam) {
        PermissionManager.TPermissionType type = PermissionManager.checkPermission(TContextWrap.of(this), invokeParam.getMethod());
        if (PermissionManager.TPermissionType.WAIT.equals(type)) {
            this.invokeParam = invokeParam;
        }
        return type;
    }

    private Uri getImageCropUri() {
        File file = new File(mImagePath, mImageName);
        path = mImagePath + mImageName;
        if (!file.getParentFile().exists()) file.getParentFile().mkdirs();
        return Uri.fromFile(file);
    }

    private void uploadFileToOSS(String iconPath) {
        String[] strings = iconPath.split("/");
        String name = strings[strings.length - 1];
        OSSClient ossClient = MyApp.getOssClient();
        // 构造上传请求。
        PutObjectRequest put = new PutObjectRequest("wlshop-app", name, iconPath);

        put.setProgressCallback(new OSSProgressCallback<PutObjectRequest>() {
            @Override
            public void onProgress(PutObjectRequest request, long currentSize, long totalSize) {
                Log.d("PutObject", "currentSize: " + currentSize + " totalSize: " + totalSize);
            }
        });

        OSSAsyncTask task = ossClient.asyncPutObject(put, new OSSCompletedCallback<PutObjectRequest, PutObjectResult>() {
            @Override
            public void onSuccess(PutObjectRequest request, PutObjectResult result) {
                runOnUiThread(new Runnable() {
                    @Override
                    public void run() {
                        Log.d("PutObject", "UploadSuccess");
                        Log.d("ETag", result.getETag());
                        Log.d("RequestId", result.getRequestId());
                        getOSSUrl = ossClient.presignPublicObjectURL("wlshop-app", name);
                        Log.d("servercallback", "1--" + getOSSUrl);
                        Glide.with(UpdateUserActivity.this).load(iconPath).apply(RequestOptions.bitmapTransform(new CircleCrop())).into(ivUpdateIcon);
                        frount_photo = getOSSUrl;
                    }
                });
            }

            @Override
            public void onFailure(PutObjectRequest request, ClientException clientExcepion, ServiceException serviceException) {
                ToastUtils.showLongToast("图片上传异常");
                // 请求异常。
                if (clientExcepion != null) {
                    // 本地异常，如网络异常等。
                    clientExcepion.printStackTrace();
                }
                if (serviceException != null) {
                    // 服务异常。
                    Log.e("ErrorCode", serviceException.getErrorCode());
                    Log.e("RequestId", serviceException.getRequestId());
                    Log.e("HostId", serviceException.getHostId());
                    Log.e("RawMessage", serviceException.getRawMessage());
                }
            }
        });
        // task.cancel(); // 可以取消任务。
        // task.waitUntilFinished(); // 等待任务完成。
    }

}
